package com.wxl.service;

import com.wxl.dao.BaseDao;
import com.wxl.pojo.HosInv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class BaseService {

    @Autowired
    private BaseDao baseDao;

    public List<HosInv> findAll(){
        return baseDao.findAll();
    }

    public Page<HosInv> pageQuery(HosInv label, int page, int size) {
//        Specification<HosInv> specification = createSpecification(label);
        Pageable pageable = PageRequest.of(page-1, size);
        return baseDao.findAll(pageable);
    }

    public Specification<HosInv> createSpecification(HosInv label){
        return new Specification<HosInv>() {
            @Override
            public Predicate toPredicate(Root<HosInv> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                if (label.getInv_name()!=null && !"".equals(label.getInv_name())){
                    Predicate predicate = criteriaBuilder.like(root.get("labelname").as(String.class), "%"+label.getInv_name()+"%");
                    predicateList.add(predicate);
                }
                return criteriaBuilder.and( predicateList.toArray( new Predicate[predicateList.size()]) );
            }
        };
    }

    public void save(HosInv hosInv){
//        label.setId(idWorker.nextId()+"");
        baseDao.save(hosInv);
    }

    public void deleteById(int id){
        baseDao.deleteById(id);
    }


}
